package drone.basis.util;

import java.util.HashMap;
import java.util.Map;

import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;

public class ExpressionUtil {

	// 简单四则运算计算
	public static Double simpleCalculate(String formula) {
		Expression expression = new ExpressionBuilder(formula).build();
		return expression.evaluate();
	}

	// 自定义函数计算 例如 3 * (y) - 2 / (x - 2)"
	public static Double customizedCalculate(String formula, Map<String, Double> params) {

		Expression expression = new ExpressionBuilder(formula).variables(params.keySet()).build();

		for (Map.Entry<String, Double> e : params.entrySet()) {
			expression.setVariable(e.getKey(), e.getValue());
		}
		return expression.evaluate();
	}

	public static void main(String[] args) {
		Map<String, Double> params = new HashMap<String, Double>();
		params.put("x", 3d);
		params.put("y", 12d);

		System.out.println(customizedCalculate("3 * (y) - 2 / (x - 2)", params));
	}
}
